package com.fullhome8.cn.wanghongweb.interceptor;

import com.fullhome8.cn.wanghongweb.annotation.Authorization;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.HashMap;

/**
 * 自定义拦截器，判断此次请求是否有权限
 */
@Component
@Slf4j
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {


	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// 如果不是映射到方法直接通过
		if (!(handler instanceof HandlerMethod)) {
			return true;
		}
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		Method method = handlerMethod.getMethod();
		Authorization auth = method.getAnnotation(Authorization.class);
		if (auth == null) { // 不需要验证的
			return true;
		}
		return true;

	}
	
    public String getRemortIP(HttpServletRequest request) {

    	if (request.getHeader("x-forwarded-for") == null) {

    	return request.getRemoteAddr();

    	}

    	return request.getHeader("x-forwarded-for");

    	}
}
